package com.gimi.cloud.jimi.client.controller.userInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.client.service.userInfo.EmergencyContactService;
import com.gimi.cloud.jimi.client.service.userInfo.RdJxlLogService;
import com.gimi.cloud.jimi.client.service.userInfo.RdJxlService;
import com.gimi.cloud.jimi.client.service.userInfo.UserInfoService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.commonService.common.CommonJxlService;
import com.gimi.cloud.jimi.dto.userInfo.RdEmergencyContactDTO;
import com.gimi.cloud.jimi.dto.userInfo.RdMiguanDTO;
import com.gimi.cloud.jimi.dto.userInfo.RdUserInfoDTO;
import com.gimi.cloud.jimi.entity.userInfo.RdJxl;
import com.gimi.cloud.jimi.entity.userInfo.RdJxlLog;
import com.gimi.cloud.jimi.dto.params.InterfaceCenterParams;
import com.gimi.cloud.jimi.dto.params.JxlResultParam;
import com.gimi.cloud.jimi.dto.params.OperatorParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 运营商验证接口
 */
@RestController
@RequestMapping(value = "operators")
public class OperatorsController {

    private static Logger logger = LoggerFactory.getLogger(OperatorsController.class);
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private EmergencyContactService emergencyContactService;
    @Autowired
    private InterfacePlatformRequestService interfacePlatformRequestService;
    @Autowired
    private RdJxlService rdJxlService;
    @Autowired
    private RdJxlLogService rdJxlLogService;
    @Autowired
    private CommonJxlService commonJxlService;

    /**
     *   提交申请表单获取回执信息  运营商
     * @throws Exception
     */
    @RequestMapping(value = "/applications")
    public void applications(@RequestBody OperatorParams opparams, HttpServletResponse response) {
        Integer  userId = opparams.getUserId();
        RdUserInfoDTO userInfo = userInfoService.getUserInfoByUserId(userId);
        RdEmergencyContactDTO ecDot = new RdEmergencyContactDTO();
        ecDot.setUserId(userId);
        RdEmergencyContactDTO emergency = emergencyContactService.findEmergencyContactByUser(ecDot);
        Response resp = new Response();
        if(userInfo == null || emergency == null) {
            resp.setResponseCode(ResponseCodeEnum.PARAMETER_ERROR);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }

        /**在调用聚信立之前先调用蜜罐接口，存储之后放入OSS*/
        logger.info("=====================调用蜜罐接口开始=========================");
        RdMiguanDTO miguanLog= commonJxlService.findIsUpload(userInfo);
        //判断是否成功上传，成功上传了的不用再调用蜜罐
        if(miguanLog==null || miguanLog.getFlag() != 1){
            try {
                commonJxlService.toGetTokenAndInfo(userInfo);
            } catch (Exception e) {
                logger.error("蜜罐接口调用失败==============="+e.getMessage()+"========================");
            }
        }
        logger.info("=====================调用蜜罐接口结束=========================");

        Map<String, Object> params = new HashMap<String, Object>();//请求主体信息
        Map<String,Object> basic_info=new HashMap<String,Object>();//用户基本信息
        List<Map<String,Object>> contacts=new ArrayList<>();//联系人信息
        basic_info.put("name", userInfo.getRealName());
        basic_info.put("id_card_num", userInfo.getCardId().toUpperCase());
        basic_info.put("cell_phone_num", userInfo.getMobilePhone());
        basic_info.put("home_addr", userInfo.getHomeAddress()==null?"":userInfo.getHomeAddress());
        //TODO 其他需要的参数
        params.put("basic_info", basic_info);

        //TODO 注意人名中包含 · 等特殊字符
        Map<String, Object> contact1 = new HashMap<>();
        contact1.put("contact_tel", emergency.getOnePhone());
        contact1.put("contact_name", emergency.getOneName());
        contact1.put("contact_type", getContactType(emergency.getOneRelationship()));
        contacts.add(contact1);
        Map<String, Object> contact2 = new HashMap<>();
        contact2.put("contact_tel", emergency.getTwoPhone());
        contact2.put("contact_name", emergency.getTwoName());
        contact2.put("contact_type", getContactType(emergency.getTwoRelationship()));
        contacts.add(contact2);
        params.put("contacts", contacts);

        //一些其他相关数据
        String[] selected_website = {};
        boolean skip_mobile=false;
        String uid="";
        params.put("selected_website", selected_website);
        params.put("skip_mobile", skip_mobile);
        params.put("uid", uid);

        try {
            //TODO 将这些移至数据库
            InterfaceCenterParams icParams = new InterfaceCenterParams("juxinli_data_source_submit","juxinliinterface");
            icParams.addParams(params);
            //访问日志
            RdJxlLog log = new RdJxlLog();
            log.setRequestParam(JsonUtil.toJson(icParams));
            log.setRequestTime(new Date());
            log.setDescription("提交申请表单获取回执信息");
            log.setRequestUrl("juxinli_data_source_submit");

            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(icParams));
            logger.info(result);
            log.setResponse(result);
            log.setResponseTime(new Date());

            JSONObject json = JSON.parseObject(result);
            JSONObject jsonHead = json.getJSONObject("head");
            String responseCode = jsonHead.getString("responseCode");
            if(!"0000".equals(responseCode)) {
                resp.setResponseCode(ResponseCodeEnum.PARAMETER_ERROR);
                resp.setRes_msg(jsonHead.getString("responseDescription"));
                Util.sendResponse(JsonUtil.toJson(resp), response);
                rdJxlLogService.saveJxlLog(log);
                return;
            }

            String token = "";
            String website = "";
            JSONObject body = json.getJSONObject("body");

            JSONObject jxlData = body.getJSONObject("data");
            if(jxlData != null) {
                token = jxlData.getString("token");
                website = jxlData.getJSONObject("datasource").getString("website");
            }
            String jxlResult=body.get("success").toString();
            String jxlCode = body.get("code").toString();
            Map<String, Object> resData = new HashMap<>();
            Map<String, Object> responseMap = new HashMap<>();
            String codeMsg = getOperatorsCodeMsg(jxlCode);
            responseMap.put("msg", codeMsg);
            responseMap.put("code", jxlCode);
            if(jxlResult.equals("true")){
                responseMap.put("success", "true");
            }else{
                responseMap.put("success", "false");
                resp.setRes_msg(body.getString("message"));
            }
            responseMap.put("rqToken", token);
            responseMap.put("website", website);
            responseMap.put("phone", userInfo.getMobilePhone());

            RdJxl jxl = rdJxlService.getNewestJxlByUser(userId);
            if(jxl == null) {
                jxl = new RdJxl();
                jxl.setAddTime(new Date());
            }
            jxl.setToken(token);
            jxl.setUserId(userId);
            jxl.setSvcMobile(userInfo.getMobilePhone());
            jxl.setUpdateTime(new Date());
            rdJxlService.saveRdJxl(jxl);
            log.setUserId(userId);
            log.setToken(token);
            log.setJxlId(jxl.getjId());
            rdJxlLogService.saveJxlLog(log);

            //resData.put("res_data", responseMap);
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
            resp.setRes_data(responseMap);
            Util.sendResponse(JsonUtil.toJson(resp), response);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setResponseCode(ResponseCodeEnum.PARAMETER_ERROR);
            Util.sendResponse(JsonUtil.toJson(resp), response);
        }
    }

    /**
     * 采集运行商数据  获取短信验证码
     * @param params
     * @param response
     */
    @RequestMapping("/collect")
    public void collect(@RequestBody OperatorParams params, HttpServletResponse response) {
        Response resp = new Response();
        Integer userId = params.getUserId();
        RdJxl jxl = rdJxlService.getNewestJxlByUser(userId);
        JxlResultParam resultParam = new JxlResultParam();
        if(jxl == null) {
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
            resultParam.setCode(JxlResultParam.RESTART);
            resultParam.setSuccess(false);
            resultParam.setMessage("请先完成信息认证");
            resp.setRes_data(resultParam);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }

        InterfaceCenterParams icParams = new InterfaceCenterParams("juxinli_request_data_source_submit", "juxinliinterface");
        //请求参数
        String password=params.getPassword();
        String token=params.getToken();
        String account= params.getAccount();
        String website= params.getWebsite();
        //TODO 聚信力日志
        String captcha= StringUtil.isBlank(params.getCaptcha())?"":params.getCaptcha();//网站短信验证码
        String queryPwd= StringUtil.isBlank(params.getQueryPwd())?"":params.getQueryPwd();;//网站查询密码
        String type="";//
        icParams.addParam("token", token);
        icParams.addParam("account", account);
        icParams.addParam("password", password);
        icParams.addParam("website", website);
        icParams.addParam("captcha", captcha);
        icParams.addParam("queryPwd", queryPwd);
        icParams.addParam("type", type);

        try {
            RdJxlLog log = new RdJxlLog();
            log.setRequestTime(new Date());
            log.setRequestParam(JsonUtil.toJson(icParams));
            log.setRequestUrl("juxinli_request_data_source_submit");
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(icParams));
            log.setResponseTime(new Date());
            log.setResponse(result);
            log.setToken(token);
            log.setUserId(params.getUserId());
            log.setDescription("采集运行商数据  获取短信验证码");
            rdJxlLogService.saveJxlLog(log);

            JSONObject resultJson = JSON.parseObject(result);
            JSONObject resultBody = resultJson.getJSONObject("body");
            logger.info(">>>>>>>>>>>>>>>>>" + resultBody);
            JSONObject resultHead = resultJson.getJSONObject("head");
            if(resultBody != null) {
                String isSuc = resultBody.getString("success");
                if ("true".equals(isSuc)) {
                    JSONObject datas = resultBody.getJSONObject("data");
                    String code = datas.getString("process_code") + "";
                    if (code.equals("10002")) {
                        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                        resp.setRes_data(resultBody);
                        logger.info(">>>>>>>>>>>>>>>>>" + JsonUtil.toJson(resp));
                        Util.sendResponse(JsonUtil.toJson(resp), response);
                        return;
                    } else {
                        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                        resp.setRes_data(resultBody);
                        logger.info(">>>>>>>>>>>>>>>>>" + JsonUtil.toJson(resp));
                        Util.sendResponse(JsonUtil.toJson(resp), response);
                        return;
                    }
                } else {
                    resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                    resp.setRes_data(resultBody);
                    logger.info(">>>>>>>>>>>>>>>>>" + JsonUtil.toJson(resp));
                    Util.sendResponse(JsonUtil.toJson(resp), response);
                    return;
                }
            } else {
                resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                resp.setRes_data(resultBody);
                logger.info(">>>>>>>>>>>>>>>>>" + JsonUtil.toJson(resp));
                Util.sendResponse(JsonUtil.toJson(resp), response);
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.setResponseCode(ResponseCodeEnum.FAILURE);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }
    }

    /**
     * 采集运行商数据  提交短信验证码
     * @param params
     * @param response
     */
    @RequestMapping("/submit")
    public void collectSubmit(@RequestBody OperatorParams params, HttpServletResponse response) {
        Response resp = new Response();
        Integer userId = params.getUserId();
        JxlResultParam resultParam = new JxlResultParam();
        RdJxl jxl = rdJxlService.getNewestJxlByUser(userId);
        if(jxl == null) {
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
            resultParam.setCode(JxlResultParam.RESTART);
            resultParam.setSuccess(false);
            resultParam.setMessage("请先完成信息认证");
            resp.setRes_data(resultParam);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }

        InterfaceCenterParams jxlParam = new InterfaceCenterParams("juxinli_request_data_source_submit","juxinliinterface");
        Map<String, Object> jxlBody = new HashMap<>();

        String password=params.getPassword();
        String token=params.getToken();
        String account=params.getAccount();
        String website=params.getWebsite();

        String captcha=params.getCaptcha().trim();//网站短信验证码
        String queryPwd= StringUtil.isBlank(params.getQueryPwd())?"":params.getQueryPwd();;//网站查询密码
        String type="";
        if(null!=captcha && !"".equals(captcha.trim())){
            type="SUBMIT_CAPTCHA";//RESEND_CAPTCHA
        }
        jxlBody.put("token", token + "");
        jxlBody.put("account", account + "");
        jxlBody.put("password", password + "");
        jxlBody.put("website", website + "");
        jxlBody.put("captcha", captcha + "");
        jxlBody.put("queryPwd", queryPwd + "");
        jxlBody.put("type", type + "");
        jxlParam.addParams(jxlBody);

        try {
            //保存聚信力日志
            RdJxlLog log = new RdJxlLog();
            log.setRequestTime(new Date());
            log.setRequestParam(JsonUtil.toJson(jxlParam));
            log.setToken(token);
            log.setUserId(params.getUserId());
            log.setRequestUrl("juxinli_request_data_source_submit");
            log.setDescription("采集运行商数据  提交短信验证码");
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(jxlParam));
            log.setResponse(result);
            log.setResponseTime(new Date());
            log.setJxlId(jxl.getjId());
            rdJxlLogService.saveJxlLog(log);
            JSONObject resultJson = JSON.parseObject(result);
            JSONObject resultBody = resultJson.getJSONObject("body");
            logger.info(">>>>>>>>>>>>>>>>>" + resultBody);
            if(resultBody != null) {
                JSONObject resultData = resultBody.getJSONObject("data");
                if(resultData != null) {
                    String processCode = resultData.getString("process_code");
                    if ("10008".equals(processCode)) {
                        int teleoperators_id = 0;
                        String teleoperators = "";
                        if (website.contains("chinamobile")) {//1
                            teleoperators_id = 1;
                            teleoperators = "中国移动";
                        }
                        if (website.contains("chinaunicom")) {//2
                            teleoperators_id = 2;
                            teleoperators = "中国联通";
                        }
                        if (website.contains("chinatelecom")) {//0
                            teleoperators = "中国电信";
                        }
                        String mobile_phone = params.getAccount();
                        String svc_pwd = password;
                        //保存运营商信息
                        //添加一条有效的token记录
                        /*RdJxl jxl = rdJxlService.getNewestJxlByUser(params.getUserId());
                        if (jxl == null) {
                            jxl = new RdJxl();
                            jxl.setAddTime(new Date());
                        }*/
                        jxl.setToken(token);
                        jxl.setSvcName(teleoperators);
                        jxl.setSvcType(teleoperators_id + "");
                        jxl.setSvcPwd(svc_pwd);
                        jxl.setSvcMobile(mobile_phone);
                        jxl.setUpdateTime(new Date());
                        rdJxlService.saveRdJxl(jxl);
                    }
                }
                resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                resp.setRes_data(resultBody);
/*                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("res_code", "0000");
                resultMap.put("res_msg", "操作成功");
                resultMap.put("res_data",resultBody);
                Util.sendResponse(JsonUtil.objectToJson(resultMap), response);
                return;*/
            } else {
                resp.setResponseCode(ResponseCodeEnum.FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setResponseCode(ResponseCodeEnum.FAILURE);
        }
        logger.info(">>>>>>>>>" + JsonUtil.toJson(resp));
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    public String getOperatorsCodeMsg(String code) {
        String msg = "";
        switch (code) {
            //验证码发送成功
            case "10002":
                msg =  "请输入验证码";
                break;
            case "10001":
                msg =  "请再次输入验证码";
                break;
            case "10006":
                msg =  "短信验证码失效系统已自动重新下发，请重新输入";
                break;
            case "10017":
                msg =  "请用本机发送CXXD至10001获取查询验证码";
                break;
            case "10018":
                msg =  "验证码失效，请用本机发送CXXD至10001获取查询验证码";
                break;
            //服务器密码错误或简单
            case "10003":
                msg = "服务密码错误，请重新输入";
                break;
            case "10007":
                msg = "简单密码或初始密码无法登录";
                break;
            case "65537":
                msg =  "机构账号不存在";
                break;
            case "65538":
                msg =  "机构账号已冻结";
                break;
            case "65539":
                msg =  "机构账号已过期";
                break;
            case "65540":
                msg =  "基本信息不能为空";
                break;
            case "65541":
                msg =  "身份证号码为空或身份证号码不合法";
                break;
            case "65542":
                msg =  "手机号码为空或手机号码不合法";
                break;
            case "65543":
                msg =  "姓名为空或姓名不合法";
                break;
            case "65544":
                msg =  "联系人姓名不合法";
                break;
            case "65545":
                msg =  "联系人手机号码不合法";
                break;
            case "65552":
                msg =  "联系人类型不合法";
                break;
            case "65553":
                msg =  "数据源名称不合法";
                break;
            case "65554":
                msg =  "手机号码不支持认证";
                break;
            case "65555":
                msg =  "手机号码所在运营商正在维护";
                break;
            case "65556":
                msg =  "生成token失败";
                break;
            case "65557":
                msg =  "生成token成功";
                break;
            //运营商异常
            case "30000":
            case "0":
            default:
                msg = "验证失败，请稍后重试。";
                break;
        }
        return msg;
    }

    /**
     * 将自定义类型转换成聚信力指定类型
     * @param scoreType
     * @return;
     */
    public String getContactType(String scoreType) {
        //数据库 联系人1,2,3,4,5,6,7,8,9  父母,配偶,亲戚,同事,朋友,其它,情侣,父母或配偶,朋友或同事
        //聚信力  "0":配偶，"1":父母，"2":兄弟姐妹,"3":子女,"4":同事,"5": 同学,"6": 朋友
        String returnType = null;
        switch (scoreType) {
        case "1":
        case "8":
        returnType = "1";
        break;
        case "2":
        returnType = "0";
        break;
        case "3":
        case "5":
        case "6":
        case "9":
        returnType = "6";
        break;
        case "4":
        returnType = "4";
        break;
        default:
        returnType = "6";
        break;
    }
        return returnType;
    }
}
